<!-- src/views/system/AclEdit.vue -->
<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { AclStores } from '@/stores/AclStores'

const aclStore = AclStores()

const emit = defineEmits(['update:visible', 'success'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  aclData: {
    type: Object,
    default: () => ({})
  }
})

const formRef = ref()
const loading = ref(false)

const form = reactive({
  id: null,
  name: '',
  code: '',
  type: null,
  url: ''
})

const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  url: [
    { required: true, message: '请输入URL地址', trigger: 'blur' }
  ]
}

// 监听权限数据变化，填充表单
watch(
    () => props.aclData,
    (newAclData) => {
      if (newAclData && Object.keys(newAclData).length > 0) {
        Object.assign(form, {
          id: newAclData.id || null,
          name: newAclData.name || '',
          code: newAclData.code || '',
          type: newAclData.type !== undefined ? Number(newAclData.type) : null,
          url: newAclData.url || ''
        })
      } else {
        // 重置表单
        Object.assign(form, {
          id: null,
          name: '',
          code: '',
          type: null,
          url: ''
        })
      }
    },
    { immediate: true, deep: true }
)

const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

const handleSubmit = async () => {
  try {
    loading.value = true
    await formRef.value.validate()

    // 准备提交的数据，确保包含所有字段
    const submitData = {
      ...form,
      type: form.type !== null ? Number(form.type) : null
    }

    // 确保更新时包含ID字段
    if (submitData.id) {
      // 更新现有权限
      await aclStore.update(submitData)
      ElMessage.success('权限更新成功')
    } else {
      // 创建新权限
      await aclStore.create(submitData)
      ElMessage.success('权限创建成功')
    }

    emit('success')
    handleClose()
  } catch (error) {
    if (error !== 'validate') {
      console.error('保存权限失败:', error)
      ElMessage.error('保存失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-dialog
      :model-value="visible"
      :title="form.id ? '编辑权限' : '新增权限'"
      width="500px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-loading="loading"
    >
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入权限名称" clearable />
      </el-form-item>

      <el-form-item label="权限编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入权限编码" clearable />
      </el-form-item>

      <el-form-item label="权限类型" prop="type">
        <el-select
            v-model="form.type"
            placeholder="请选择权限类型"
            style="width: 100%"
            clearable
        >
          <el-option label="API" :value="1" />
          <el-option label="菜单" :value="2" />
          <el-option label="按钮" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="URL地址" prop="url">
        <el-input v-model="form.url" placeholder="请输入URL地址" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
